package com.smedi.ismedi.inmail.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.geo.Location;
import com.smedi.ismedi.inmail.core.domain.repository.LocationRepository;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.model.LocationEntity;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.mybatis.mapper.LocationMapper;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.stereotype.Repository;

/**
 * 基础信息仓库实现类
 *
 * @author jiangqinxuan
 * @date 2021/08/03
 */
@Repository
@AllArgsConstructor
public class LocationRepositoryImpl extends ServiceImpl<LocationMapper, LocationEntity> implements LocationRepository, IService<LocationEntity> {
    private final DozerUtil dozerUtil;

    private final LocationMapper locationMapper;


    @Override
    public void insertLocation(@NonNull Location location) {
        LocationEntity locationEntity = dozerUtil.convertor(location, LocationEntity.class);
        locationEntity.setLocationId(location.getId());
        locationEntity.setId(null);
        locationMapper.insert(locationEntity);
    }

    @Override
    public Long getLocationIdByName(@NonNull String name) {
        LambdaQueryWrapper<LocationEntity> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(LocationEntity::getName, name);
        queryWrapper.last("limit 1");

        LocationEntity locationEntity = this.baseMapper.selectOne(queryWrapper);
        if (null != locationEntity) {
            return locationEntity.getLocationId();
        }

        return 0L;
    }
}